<script setup lang="ts">
import {useRouter, useRoute} from 'vue-router'
import type {FormInstance, FormRules, UploadInstance, UploadProps, UploadRawFile} from 'element-plus'
import {genFileId} from 'element-plus'
import {reactive, ref, h} from 'vue'
import {Server} from '../stores/ajax';
import {Delete, Download, Plus, ZoomIn} from '@element-plus/icons-vue'
import {Delta, QuillEditor} from '@vueup/vue-quill'
import type {Sources} from 'quill';
import Quill from 'quill';
import BlotFormatter from 'quill-blot-formatter'
import MarkdownShortcuts from 'quill-markdown-shortcuts';
import ImageUploader from "quill-image-uploader"
const ImageBase = Quill.import('formats/image');

const ATTRIBUTES = [
    'alt',
    'height',
    'width',
    'style' // This is the added difference that needs to be saved properly
];

class CustomImage extends ImageBase {
    declare domNode: any; // Needed declaration for Typescript

    static formats(domNode: any) {
        return ATTRIBUTES.reduce((formats, attribute) => {
            const copy: any = {...formats};

            if (domNode.hasAttribute(attribute)) {
                copy[attribute] = domNode.getAttribute(attribute);
            }

            return copy;
        }, {});
    }

    format(name: any, value: any) {
        if (ATTRIBUTES.indexOf(name) > -1) {
            if (value) {
                this.domNode.setAttribute(name, value);
            } else {
                this.domNode.removeAttribute(name);
            }
        } else {
            super.format(name, value);
        }
    }
}

Quill.register('formats/image', CustomImage);
let tableData = $ref([

])
const modules = $ref([
    {
        name: 'MarkdownShortcuts',
        module: MarkdownShortcuts,
        options: {/* options */}
    },

    {
        name: 'imageUploader',
        module: ImageUploader,
        options: {
            upload: (file: any) => {
                let data = {
                    image: file
                }
                return new Promise((resolue, reject) => {
                    Server.axios.post("/file/upload_image", data, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then((res) => {
                        Server.checkShowMessage(res)
                        if (res.data.code == 0) {
                            resolue(Server.fileBaseURL + res.data.return)
                        } else {
                            reject("服务器错误")
                        }
                    }).catch(reject)
                    // console.log(file)

                })
            }
        }
    }
])
const submitDeleteArticle = async (modifyArticleData: any) => {
    console.log(modifyArticleData)
    await Server.axios.delete('/content/delete_article?aid=' + modifyArticleData.article.aid).then((res) => {
        Server.checkShowMessage(res)
        if (res.data && res.data.code == 0) {
            refresh()
            removeTab(modifyArticleData.name)
        }
    }).catch(console.log)
}
let modifyArticleVisiable = $ref(false)
let addTeamRouteName = $ref("")
const upload = ref<UploadInstance>()

const ruleFormRef = $ref<FormInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
const refresh = async () => {
    
}
refresh()

const submitModifyArticle = async (articleItem: any) => {
    let articleData = articleItem.article
    console.log(articleData)
    let data = {...articleData}
    data.content = JSON.stringify(data.content)
    await Server.axios.post(`/content/${articleData.aid ? 'modify_article' : 'upload_article'}`, data, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
    ).then((res) => {
        Server.checkShowMessage(res)
        if (res.data && res.data.code == 0) {
            articleItem.title = articleData.title
            if (!articleItem.article.aid)// 上传时返回id
                articleItem.article.aid = res.data.return
            refresh()
        }
    }).catch(err => console.log)
}


let tabIndex = 2
const editableTabsValue = ref('2')
const editableTabs = ref([
    {
        title: 'Tab 1',
        name: '1',
        article: {
            aid: 0,
            title: "",
            content: {}
        },
    },
])
editableTabs.value = []
editableTabsValue.value = "__all"
const addTab = (targetName: string) => {
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
        title: '未命名',
        name: newTabName,
        article: {
            aid: 0,
            title: "",
            content: {}
        },
    })
    editableTabsValue.value = newTabName
}
let sometext = $ref("fefefefef")
const handleModifyArticle = (index: number, row: any) => {

    let tab = editableTabs.value.filter((tab) => tab.article.aid == row.aid)// 文章的aid是唯一的，可用于找对应的tab
    if (tab.length) {
        editableTabsValue.value = tab[0].name
        return
    }
    const newTabName = `${++tabIndex}`
    // console.log(row.content)
    let content: Object = row.content instanceof Object ? row.content : {}
    if (typeof row.content == 'string') {
        try {
            content = JSON.parse(row.content)
        } catch (e) {content = {}}
    }
    console.log(content)
    editableTabs.value.push({
        title: row.title,
        name: newTabName,
        article: {
            aid: row.aid,
            title: row.title,
            content
        },
    })
    editableTabsValue.value = newTabName
}
const removeTab = (targetName: string) => {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
        tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeName = nextTab.name
                }
            }
        })
    }

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
    if (!editableTabs.value.length) editableTabsValue.value = "__all"
}
const handleTextChange = (delta: Delta, oldContents: Delta, source: Sources) => {
    // console.log(delta)
}
const search = $ref('')
const filterTableData = $computed(() =>
    tableData.filter(
        (data) =>
            !search ||
            (data as any).title.toLowerCase().includes(search.toLowerCase())
    )
)
</script>

<template>

    <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" @tab-remove="removeTab">
        <el-tab-pane label="所有文章" name="__all">
            <div class="fh" style="justify-content: start;">
                <el-button @click="addTab(editableTabsValue)">
                    添加文章
                </el-button>
                <el-button @click="refresh">刷新</el-button>
                <div style="flex-grow: 1; justify-content: end;" class="fh">
                    <el-input style="width: 200px; " v-model="search" size="small" placeholder="按路标题搜索" />
                </div>
            </div>
            <el-table :data="filterTableData" style="width: 100%">
                <el-table-column fixed prop="aid" label="id" width="90" sortable />

                <el-table-column prop="title" label="标题" width="150" sortable />
                <el-table-column prop="create_time" label="添加时间" width="150" sortable />
                <el-table-column prop="modify_time" label="修改时间" width="150" sortable />
                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <el-button @click="handleModifyArticle(scope.$index, scope.row)" link type="primary"
                            size="small">
                            详情/修改
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-tab-pane>
        <el-tab-pane closable v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
            <div class="fh" style="gap:20px; margin-bottom: 15px;">
                <el-input v-model="item.article.title" />
                <el-button @click="submitModifyArticle(item)">{{ !item.article.aid ? '添加文章' : '修改文章'}}
                </el-button>
            <el-popconfirm title="确定要删除吗?" @confirm="submitDeleteArticle(item)">
                <template #reference>
                <el-button v-if="item.article.aid" >删除文章
                </el-button>
                </template>
            </el-popconfirm>
            </div>

            <QuillEditor :modules="modules" toolbar="full" theme="snow" v-model:content="item.article.content as any"
                content-type="delta" style="height: 430px;" placeholder="输入文字" @textChange="handleTextChange" />
        </el-tab-pane>
    </el-tabs>
    <br />
</template>

<style>
.el-tabs__content {
    overflow: visible;
}
</style>
